package cn.campsg.messageboard.controller.Admin;

import cn.campsg.messageboard.model.User;
import cn.campsg.messageboard.model.Message;
import cn.campsg.messageboard.utils.DBUtil;
import jakarta.servlet.ServletException;
import jakarta.servlet.annotation.WebServlet;
import jakarta.servlet.http.HttpServlet;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.sql.*;
import java.util.ArrayList;
import java.util.List;

@WebServlet("/MessageManagementServlet")
public class MessageManagementServlet extends HttpServlet {
    protected void doGet(HttpServletRequest request, HttpServletResponse response)
            throws ServletException, IOException {

        // 检查管理员登录
        if (request.getSession().getAttribute("admin") == null) {
            response.sendRedirect("admin_login.jsp");
            return;
        }

        try (Connection conn = DBUtil.getConnection()) {
            // 获取所有留言
//            String messageSql = "SELECT m.*, u.username FROM message m JOIN user u ON m.user_id = u.id";
//            String messageSql = "SELECT * FROM message";
            String sql = "SELECT * FROM message ORDER BY created_at DESC";
            Statement stmt = conn.createStatement();
            ResultSet rs = stmt.executeQuery(sql);
            List<Message> messages = new ArrayList<>();
            while (rs.next()) {
                Message msg = new Message();
                msg.setId(rs.getInt("id"));
                msg.setContent(rs.getString("content"));
                msg.setUsername(rs.getString("username"));
                msg.setCreatedAt(rs.getTimestamp("created_at"));
                msg.setStatus(rs.getInt("status"));
                messages.add(msg);
            }

            // 获取所有用户
            String userSql = "SELECT * FROM user";
            rs = stmt.executeQuery(userSql);
            List<User> users = new ArrayList<>();
            while (rs.next()) {
                User user = new User();
                user.setId(rs.getInt("id"));
                user.setUsername(rs.getString("username"));
                user.setEmail(rs.getString("email"));
                user.setCreatedAt(rs.getTimestamp("created_at"));
//                user.setActive(rs.getBoolean("active"));
                users.add(user);
            }

            request.setAttribute("messages", messages);
            request.setAttribute("users", users);
            request.getRequestDispatcher("admin_dashboard.jsp").forward(request, response);

        } catch (SQLException e) {
            throw new ServletException(e);
        }
    }
}